/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
class Solution {
public:
    vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
    	vector<Interval> result;

		if (intervals.size() == 0 || newInterval.end < intervals[0].start) {
			result.push_back(newInterval);
			for (int i = 0; i < intervals.size(); ++i) {
				result.push_back(intervals[i]);
			}
		} else if (intervals[intervals.size() - 1].end < newInterval.start) {
			for (int i = 0; i < intervals.size(); ++i) {
				result.push_back(intervals[i]);
			}
			result.push_back(newInterval);
		} else {
			int i = 0;
			while (i < intervals.size() && intervals[i].end < newInterval.start) {
				result.push_back(intervals[i]);
				++i;
			}
			int j = i;
			while (j < intervals.size() && intervals[j].start <= newInterval.end) {
				++j;
			}
			result.push_back(Interval(min(intervals[i].start, newInterval.start),
							 max(intervals[j - 1].end, newInterval.end)));
			for (; j < intervals.size(); ++j) {
				result.push_back(intervals[j]);
			}
		}
		return result;
    }
};